﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Zhaoxi.ThreadShow.Common;

namespace Zhaoxi.ThreadShow
{
    public partial class frmSSQ : Form
    {
        /// 多线程双色球项目--
        /// 1 理解需求:
        /// 双色球：投注号码由6个红色球号码和1个蓝色球号码组成。
        /// 红色球号码从01--33中选择,不重复
        /// 蓝色球号码从01--16中选择 
        public frmSSQ()
        {
            InitializeComponent();
        }


        #region Data 
        /// <summary>
        /// 红球集合  其实可以写入配置文件
        /// </summary>
        private string[] RedNums =
        {
            "01","02","03","04","05","06","07","08","09","10",
            "11","12","13","14","15","16","17","18","19","20",
            "21","22","23","24","25","26","27","28","29","30",
            "31","32","33"
        };

        /// <summary>
        /// 蓝球集合
        /// </summary>
        private string[] BlueNums =
        {
            "01","02","03","04","05","06","07","08","09","10",
            "11","12","13","14","15","16"
        };

        private bool IsGoOn = true;
        private List<Task> taskList = new List<Task>();

        #endregion




        /// <summary>
        /// 点击开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            #region 初始化动作
            this.btnStart.Text = "运行ing";
            this.IsGoOn = true;
            this.btnStart.Enabled = false;
            this.btnStop.Enabled = true;
            this.lblBlue.Text = "00";
            this.lblRed1.Text = "00";
            this.lblRed2.Text = "00";
            this.lblRed3.Text = "00";
            this.lblRed4.Text = "00";
            this.lblRed5.Text = "00";
            this.lblRed6.Text = "00";
            #endregion 

            foreach (var control in this.gboSSQ.Controls)
            {
                if (control is Label)
                {
                    Label label = (Label)control;
                    if (label.Name.Contains("Blue")) //蓝球
                    {
                        taskList.Add(Task.Run(() =>
                       {
                           while (IsGoOn)
                           {
                               //1.应该到数组中随机的获取蓝色球（索引获取 保证随机性）
                               //2.赋值 
                               //3.循环
                               //int index = new Random().Next(0, 15); 
                               int index = new RandomHelper().GetRandomNumberDelay(0, 16);
                               string Num = BlueNums[index];
                               //label.Text = Num; //主线程创建的Label 不允许子线程来改变参数
                               this.Invoke(new Action(() =>
                               {
                                   label.Text = Num;  //委托主线程来帮我赋值
                                }));
                           }
                       }));
                    }
                    else if (label.Name.Contains("Red")) //红色球
                    {
                        taskList.Add(Task.Run(() =>
                       {
                           //1.从数组移除
                           //2.记录已经用过的
                           //3.每次生成时，获取其它lable的值，然后排除掉
                           //4.把所有的球，随机加到queue，每次读取一个queue
                           //5.结果出现重复重抽

                           //重抽会不会运气不好，线程一直等的，有点球一直出不来
                           while (IsGoOn)
                           {
                               int index = new RandomHelper().GetRandomNumberDelay(0, 33);
                               string Num = RedNums[index];

                               //1.要把界面上的值获取到
                               //2.判断当前要赋的值是否在界面中已经存在
                               lock (obj_Lock)
                               {
                                   List<string> useNumberList = GetUserRedNumbers();
                                   if (!useNumberList.Contains(Num))
                                   {
                                       this.Invoke(new Action(() =>
                                       {
                                           label.Text = Num;
                                       }));
                                   }
                                   else
                                   {
                                       //继续循环 
                                   }
                               }
                           }
                       }));
                    }
                }
            }

            Task.Factory.ContinueWhenAll(taskList.ToArray(), t =>
            {
                this.Invoke(new Action(() =>
                {
                    this.btnStart.Text = "Start";
                    this.btnStart.Enabled = true;
                    this.btnStop.Enabled = false;
                })); 
                ShowResult(); 
            });

        }


        private static readonly object obj_Lock = new object();

        private List<string> GetUserRedNumbers()
        {
            List<string> useNumberlist = new List<string>();
            foreach (var control in this.gboSSQ.Controls)
            {
                if (control is Label)
                {
                    if (((Label)control).Name.Contains("Red"))
                    {
                        useNumberlist.Add(((Label)control).Text);
                    }
                }

            }

            if (useNumberlist.Distinct<string>().Count() < 6 && !useNumberlist.Contains("00"))
            {
                Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
                foreach (var num in useNumberlist)
                {
                    Console.WriteLine($"this is {num}");
                }
            }


            return useNumberlist;
        }

        /// <summary>
        /// 点击结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            //1.应该让线程停止下来；
            //2.展示界面上的出现的红色球 和蓝色球的结果

            this.IsGoOn = false;
            //Task.WaitAll(this.taskList.ToArray()); //会死锁 
            //Task.Run(() =>
            //{
            //    Task.WaitAll(this.taskList.ToArray()); 
            //    ShowResult();
            //}); 
        }


        /// <summary>
        /// 弹框提示数据
        /// </summary>
        private void ShowResult()
        {
            MessageBox.Show(string.Format("本期双色球结果为：{0} {1} {2} {3} {4} {5}  蓝球{6}"
                , this.lblRed1.Text
                , this.lblRed2.Text
                , this.lblRed3.Text
                , this.lblRed4.Text
                , this.lblRed5.Text
                , this.lblRed6.Text
                , this.lblBlue.Text));
        }

    }
}
